function [crdte aircraftOut engineOut]=calculateCrdte(aircraftIn, designIn, companyIn, engineIn)
% Function that estimates research, development, test and evaluation of aircraft cost
%
% INPUT:
%   engine [struct]
%   company [struct]
%   design [struct]
%   aircraft [struct]
%
% OUTPUT:
%   ep [int]
%
% LIMITATIONS/RESTRICTIONS:
%   Engine`s shp must be grater than 400
%
% AUTHOR: Pietro A R Cerchiari
% REVISION:2.0

%% Load Data
MTOW=aircraftIn.weights.mtow;
Vc=aircraftIn.cruiseSpeed;
nbEngines=engineIn.quantity;

if isfield(aircraftIn,'avionicsPrice')
    Cavionics=aircraftIn.avionicsPrice;
else
    error('Enter avionics price');
end

Cmhaed=companyIn.engineeringCost;
Cmhman=companyIn.manufacturingCost;
Cmhtool=companyIn.toolingCost;
Fpro=companyIn.estimatedProfit;

Nrdte=designIn.nbPrototypes;
Nst=Nrdte-designIn.nbCompletePrototypes;
nM=Nrdte;

%% Inicialisation
CEF=2.05;%5.8;%cost escalation factor, valor atualizado para 2011

%% Preliminary calculations
We=0.599361*MTOW+35.15;
engineOut=engineIn;

%Estiamte shp
if ~isfield(engineOut,'shpTakeOff')
    engineOut.shpTakeOff=(4.7175*(aircraftIn.weights.mtow*aircraftIn.cruiseSpeed/10000)+107.54)/engineOut.quantity;
end

%Estimate engine price
if isfield(engineOut,'price')
    Cengine=engineOut.price;
else
    Cengine=calculateEngineCost(engineOut);
    engineOut.price=Cengine;
end

%% airframe engineering and design cost
factor=1.8;
MHaed = (4.86*We^0.777*Vc^0.894*nM^0.163)*factor;
Caed=MHaed*Cmhaed;

%% support and testing cost
Cst = 45.42*We^0.630*Vc^1.3*CEF;
%% tooling cost
MHtool = 5.99*We^0.777*Vc^0.696*nM^0.263;
Ctool=MHtool*Cmhtool;
%% Prototype cost
%manufacturing labor cost
MHman = (7.37*We^0.82*Vc^0.484*nM^0.641);
Cman=MHman*Cmhman;
%quality control cost
Cq=0.133*Cman;
%material cost
Cmat = 11.0*We^0.921*Vc^0.621*nM^0.799*CEF;
%engine and avionics cost
Cea=(nbEngines*Cengine+Cavionics)*(Nrdte-Nst); %custo motores + avionicos
%total prototype cost
Cfta=Cea+Cman+Cmat+Cq;

%% flight test operation cost
Cfto = 1243.03*We^0.325*Vc^0.822*(Nrdte-Nst)^1.21*CEF;

%% final cost
crdte=(Caed+Cst+Cfta)/(1-Fpro);
Cfin=crdte-(Caed+Cst+Cfta);

%% Export costs
manHours.mhAedD=MHaed;
costs.cAedD=Caed;
costs.cStD=Cst;
costs.cEaD=Cea;
manHours.mhManD=MHman;
costs.cManD=Cman;
costs.cMatD=Cmat;
manHours.mhToolD=MHtool;
costs.cToolD=Ctool;
costs.cQD=Cq;
costs.prototypes=Cfta;
costs.cFtoD=Cfto;
costs.crdte=crdte;
costs.cFinD=Cfin;

aircraftOut=aircraftIn;
aircraftOut.costs=costs;
aircraftOut.manHours=manHours;
aircraftOut.weights.we=We;
